package face.pay.api.payter.channel.paytype.wechat.api;

import com.face.pay.WxApiConfig;
import com.github.wxpay.sdk.WXPayRequest;
import com.github.wxpay.sdk.WXPayUtil;
import face.pay.api.payter.channel.paytype.AbstractApi;
import face.pay.dao.OemInfoDao;
import face.pay.dao.OrderInfoDao;
import face.pay.dao.StoreInfoDao;
import face.pay.entity.OemInfo;
import face.pay.entity.OrderInfo;
import face.pay.api.wechat.param.QqueryParam;
import face.pay.util.bean.JavaBeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @Auther: zkj
 * @Date: 2019/9/11 14:08
 * @Description:
 */
@Slf4j
@Component
public class ApiWxPayQuery extends AbstractApi {

    private static final String domain = "api.mch.weixin.qq.com";

    private static final String urlSuffix = "/pay/orderquery";

    @Autowired
    private OrderInfoDao orderInfoDao;

    @Autowired
    private OemInfoDao oemInfoDao;

    @Autowired
    private StoreInfoDao storeInfoDao;


    @Async
    public void orderStatusCheck(Long orderId, String subMchId, WxApiConfig wxApiConfig, OemInfo oemInfo) {
        log.info(">>>>>>开始向微信查询扫码支付订单:" + orderId);


        OrderInfo orderInfo = this.orderInfoDao.getById(orderId);
        if (null == orderInfo) {
            return;
        }


        QqueryParam param = new QqueryParam();

        Integer oemId = orderInfo.getOemId();

        String appId = wxApiConfig.getAppID();
        String apiKey = wxApiConfig.getKey();
        String mchId = wxApiConfig.getMchID();

        String openId = orderInfo.getPayUserSign();
        String trade_no =orderInfo.getTradeNo();

        param.setAppid(appId);
        param.setMch_id(mchId);
        param.setSub_mch_id(subMchId);
        param.setOut_trade_no(String.valueOf(orderId));

        String nonce_str = WXPayUtil.generateNonceStr();

        param.setNonce_str(nonce_str);

        Map<String, String> map = JavaBeanUtils.toMap(param);


        try {
            String xml = WXPayUtil.generateSignedXml(map, apiKey);
            log.info("扫码支付查询>>>>>推送到微信服务器消息xml" + xml);


            Integer i = 0;

            Boolean isEnd = false;

            Thread.sleep(1000);
            while (i < 20 && !isEnd) {
                WXPayRequest wxPayRequest = new WXPayRequest(wxApiConfig);

                String result = wxPayRequest.requestOnce(domain, urlSuffix, xml, false);
                log.info("扫码支付订单查询<<<<<<返回结果 " + result);
                Map<String, String> resultMap = WXPayUtil.xmlToMap(result);
                log.info("查询结果:" + result);
                if (WXPayUtil.isSuccess(resultMap)) {
                    //查询成功  取出交易状态
                    String trade_state = resultMap.get("trade_state");
                    //订单描述信息
                    String message = resultMap.get("trade_state_desc");

                    /**
                     *1支付成功(SUCCESS)
                     * -5 转入退款(REFUND)
                     * 0未支付(NOTPAY USERPAYING)
                     * -4关闭(CLOSED)
                     * -3取消(REVOKED)
                     * -1支付失败(PAYERROR)
                     * -2下单失败(ERROR)
                     */
                    switch (trade_state) {
                        case "SUCCESS": {
                            //1支付成功(SUCCESS)
                            isEnd = true;
                            if(StringUtils.isBlank(openId)){
                                openId =resultMap.get("openid");
                            }
                            if(StringUtils.isBlank(trade_no)){
                                trade_no =resultMap.get("transaction_id");

                            }
                            updateOrderStatus( orderId,openId, trade_no,1, message);

                            /**
                             * 发送分润通知
                             */
                            orderInfo.setStatus(1);
                            orderInfo.setMessage("支付成功");

                            this.sendAllMessage(orderInfo,oemInfo.getType());
                            break;
                        }
                        //-5 转入退款(REFUND)
                        case "REFUND": {
                            isEnd = true;
                            updateOrderStatus(orderId,null,null, -5, message);
                            break;
                        }
                        //0未支付(NOTPAY未支付 USERPAYING支付中)
                        case "USERPAYING": {
                            // updateOrderStatus(orderId,0,message);
                            break;
                        }
                        case "NOTPAY": {
                            //updateOrderStatus(orderId,0,message);
                            break;
                        }
                        //-3取消(REVOKED)
                        case "REVOKED": {
                            isEnd = true;
                            updateOrderStatus(orderId,null,null, -3, message);
                            break;
                        }
                        //-4关闭(CLOSED)
                        case "CLOSED": {
                            isEnd = true;
                            updateOrderStatus(orderId,null,null, -4, message);
                            break;
                        }
                        //-1支付失败(PAYERROR)
                        case "PAYERROR": {
                            isEnd = true;
                            updateOrderStatus(orderId, null,null,-1, message);
                            break;
                        }
                        //-2下单失败(ERROR)
                        case "ERROR": {
                            isEnd = true;
                            updateOrderStatus(orderId,null, null,-2, message);
                            break;
                        }

                    }
                    log.info("<<<<<<<结束微信扫码支付订单查询:" + orderId);
                }
                Thread.sleep(3000);
                i++;
            }


        } catch (Exception e) {
            log.info("微信扫码支付订单查询异常" + e);
        }


    }


    /**
     * 更新订单状态和信息
     */
    private void updateOrderStatus(Long orderId,String openId,String trade_no, Integer status, String message) {
        OrderInfo record = new OrderInfo();
        record.setId(orderId);
        record.setStatus(status);
        record.setPayUserSign(openId);
        record.setProfitSign(0);
        record.setTradeNo(trade_no);
        record.setMessage(message);
        this.orderInfoDao.updatePayInfo(record);
    }




}
